package com.IClass.IActivity;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import com.IClass.CameraPreview;
import com.IClass.App.R;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;

public class CameraActivity extends Activity {
	/** Called when the activity is first created. */
	/** 图片媒体类型 **/  
    public static final int MEDIA_TYPE_IMAGE = 1;  
	 /** 摄像头类的对象 **/  
    private Camera mCamera;  
    /** 拍照按钮 **/  
    private Button captureButton;  
    /** 返回摄像头 **/  
    private Button cameraButton;  
    /** SurfaceView对象 **/  
    private CameraPreview mPreview; 

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);  
		Window window = getWindow();// 得到窗口  
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏  
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 保持屏幕亮  
        setContentView(R.layout.ilook_camera2_layout); 
        captureButton = (Button) findViewById(R.id.button_capture);  
        captureButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// 启动自动对焦
				
				mCamera.autoFocus(new AutoFocusCallback() {
					
					@Override
					public void onAutoFocus(boolean success, Camera camera) {
						// TODO Auto-generated method stub
						
					}
				});
				
				Timer timer = new Timer();
				timer.schedule(new TimerTask(){

					@Override
					public void run() {
						//拍照函数
						mCamera.takePicture(mShutter, null, mPicture);
					}
					
				}, 1750);
			}
		});
        
        cameraButton = (Button) findViewById(R.id.button_camera);  
        cameraButton.setOnClickListener(new OnClickListener() {  
  
            @Override  
            public void onClick(View v) {  
                // 返回按钮（拍完照片之后需要重新启动Camera的Preview）  
                mCamera.startPreview();  
            }  
        });  
        // 获取Camera对象的实例  
        mCamera = getCameraInstance();  
        // 初始化SurfaceView  
        mPreview = new CameraPreview(this,mCamera);  
        mPreview.setZOrderOnTop(true);
       
        FrameLayout  preview = (FrameLayout ) findViewById(R.id.camera_preview);  
        // 将SurfaceView添加到FrameLayout中  
        preview.addView(mPreview);  
        // 设置相机的属性  
        Camera.Parameters params = mCamera.getParameters();  
        // JPEG质量设置到最好  
        params.setJpegQuality(100);  
        // 散光灯模式设置为自动调节  
        params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);  
        mCamera.setParameters(params);  

	}
	
	public static Camera getCameraInstance() {  
        Camera c = null;  
        try {  
            c = Camera.open();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return c;  
    }  
	
	 // 快门的回调函数实现  
    private ShutterCallback mShutter = new ShutterCallback() {  
        @Override  
        public void onShutter() {  
  
        }  
    };  
    
    // PictureCallback回调函数实现  
    private PictureCallback mPicture = new PictureCallback() {  
        @Override  
        public void onPictureTaken(byte[] data, Camera camera) {  
            File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);  
            if (pictureFile == null) {  
                return;  
            }  
            // 将照片数据data写入指定的文件  
            try {  
                FileOutputStream fos = new FileOutputStream(pictureFile);  
                fos.write(data);        
                fos.close();  
                //拍照完成后，上传图片
//                Log.e("upload","length:"+ pictureFile.length());
//                Upload.uploadPhoto(pictureFile.getPath());
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            } finally{
            	mCamera.startPreview();  
            	//通过Intent传递图片路径  ,拍照完成后，显示图片到屏幕
              /*  Intent intent = new Intent();  
                intent.putExtra("picPath", pictureFile.getPath());
                intent.setClass(CameraActivity.this, PhotoViewActivity.class);
                startActivity(intent);  
                */
            }
        }  
    };  


	
	/** 
     * 在指定路径创建照片文件 
     *  
     * @param type 
     * @return 
     */  
    public static File getOutputMediaFile(int type) {  
        // 指定照片存放的目录，在SD根目录下的一个文件夹中  
        File mediaStorageDir = new File(  
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),  
                "CameraUseApp");  
      
        // 文件夹不存在，则创建该文件夹  
        if (!mediaStorageDir.exists()) {  
            if (!mediaStorageDir.mkdirs()) {  
                Log.d("CameraUse", "failed to create directory");  
                return null;  
            }  
        }  
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")  
                .format(new Date());  
        // 创建照片文件  
        File mediaFile;  
      
        if (type == MEDIA_TYPE_IMAGE) {  
            mediaFile = new File(mediaStorageDir.getPath() + File.separator  
                    + "101_20120326195110.jpg");  
            System.out.println(mediaFile.getPath());
           
        } else {  
            return null;  
        }  
        return mediaFile;  
    }  
    
    // 释放Camera对象（务必实现）  
    private void releaseCamera() {  
        if (mCamera != null) {  
            mCamera.release();  
            mCamera = null;  
        }  
    } 
    
    @Override  
    public boolean onTouchEvent(MotionEvent event) {  
        // 触摸屏幕自动对焦  
        if (event.getAction() == MotionEvent.ACTION_DOWN) {  
            mCamera.autoFocus(new AutoFocusCallback() {  
                @Override  
                public void onAutoFocus(boolean success, Camera camera) {  
  
                }  
            });  
        }  
        return super.onTouchEvent(event);  
    }  
  
    @Override  
    protected void onPause() {  
        super.onPause();  
        releaseCamera();  
    }  
}
